import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:reping/api.dart';
import 'package:reping/global.dart';
import 'package:flutter/material.dart';
import 'package:reping/toast.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '抑云热评墙',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey globalKey = GlobalKey();
  var _data;
  var _showBtn = true;

  Future<Uint8List> _capturePng() async {
    setState(() {
      _showBtn = false;
    });

    try {
      Future.delayed(Duration(milliseconds: 100), () async {
        RenderRepaintBoundary boundary =
            globalKey.currentContext.findRenderObject();
        var image = await boundary.toImage(pixelRatio: 3.0);
        ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
        Uint8List pngBytes = byteData.buffer.asUint8List();
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 100, name: "网易云热评");
        Toast.show(context,
            msg: '图片保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
        setState(() {
          _showBtn = true;
        });
      });
    } catch (e) {
      print(e);
      setState(() {
        _showBtn = true;
      });
    }
    return null;
  }

  @override
  void initState() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight]);
    getData();
    super.initState();
  }

  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    super.dispose();
  }

  getData() async {
    setState(() => {_data = null});
    var res = await reping();
    setState(() => {_data = res});
  }

  getFontSize(width, comment) {
    return width / (comment.split('').toList().length / 4);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _data == null
          ? Container(
              decoration: BoxDecoration(
                color: Global.backgroundColor,
                image: DecorationImage(
                  image: AssetImage("assets/images/bg.png"),
                  repeat: ImageRepeat.noRepeat,
                  fit: BoxFit.fitHeight,
                ),
              ),
              child: Center(
                child: CircularProgressIndicator(
                  backgroundColor: Global.backgroundColor,
                  valueColor: AlwaysStoppedAnimation<Color>(Global.fontColor),
                ),
              ),
            )
          : RepaintBoundary(
              key: globalKey,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                decoration: BoxDecoration(
                  color: Global.backgroundColor,
                ),
                child: Stack(
                  children: [
                    Positioned(
                      top: 20,
                      left: 80,
                      right: 60,
                      bottom: 80,
                      child: Container(
                        decoration: BoxDecoration(
                          color: Global.backgroundColor,
                          border: Border.all(
                            color: Global.fontColor,
                            width: 1.5,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      top: 40,
                      left: 60,
                      right: 80,
                      bottom: 60,
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Global.fontColor,
                            width: 1.5,
                          ),
                          color: Global.backgroundColor,
                        ),
                        padding: EdgeInsets.all(13),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              _data['comment_content'],
                              style: TextStyle(
                                color: Global.fontColor,
                                fontSize: 18,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(
                                  '来自用户${_data['user_name']}在《${_data['song_name']}》的评论',
                                  style: TextStyle(
                                      color: Global.fontColor, fontSize: 13),
                                ),
                              ],
                            )
                          ],
                        ),
                      ),
                    ),
                    _showBtn
                        ? Positioned(
                            bottom: 0,
                            right: 60,
                            child: Row(
                              children: [
                                IconButton(
                                  icon: Icon(Icons.refresh),
                                  color: Global.fontColor,
                                  iconSize: 30,
                                  onPressed: () {
                                    getData();
                                  },
                                ),
                                IconButton(
                                  icon: Icon(Icons.file_download),
                                  color: Global.fontColor,
                                  iconSize: 30,
                                  onPressed: () {
                                    _capturePng();
                                  },
                                ),
                              ],
                            ),
                          )
                        : Container()
                  ],
                ),
              ),
            ),
    );
  }
}
